

package com.maoshi.shop.security.multishop.controller;


import com.maoshi.shop.bean.model.ShopDetail;
import com.maoshi.shop.common.annotation.SysLog;
import com.maoshi.shop.dao.ShopDetailMapper;
import com.maoshi.shop.security.comment.model.UpdatePasswordDto;
import com.maoshi.shop.security.multishop.util.SecurityUtils;
import com.maoshi.shop.service.ShopDetailService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;

/**
 * 登录相关
 * @author lgh
 */
@Controller
@AllArgsConstructor
@ApiIgnore
@RequestMapping("/multishop")
public class MultishopLoginController {

	private final ShopDetailService shopDetailService;

	private final PasswordEncoder passwordEncoder;

	/**
	 * ping
	 */
	@GetMapping(value = "/ping")
	public ResponseEntity<Void> ping() {
		return ResponseEntity.ok().build();
	}

	/**
	 * 退出
	 */
	@PostMapping(value = "/logout")
	public ResponseEntity<String> logout() {
		SecurityContextHolder.clearContext();
		return ResponseEntity.ok().build();
	}


	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	@ApiOperation(value="修改密码", notes="修改当前登陆用户的密码")
	public ResponseEntity<String> password(@RequestBody @Valid UpdatePasswordDto param){
		String username = SecurityUtils.getShopUser().getRealUsername();

		ShopDetail shopDetail = shopDetailService.getShopByMobile(username);
		if (!passwordEncoder.matches(param.getPassword(), shopDetail.getPassword())) {
			return ResponseEntity.badRequest().body("原密码不正确");
		}
		//新密码
		String newPassword = passwordEncoder.encode(param.getNewPassword());
//		更新密码
		shopDetailService.updatePasswordByUserName(username, newPassword);
		return ResponseEntity.ok().build();
	}

}
